package com.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt过滤器对象
 * 通过AOP实现对请求的拦截过滤
 *
 * @author a0112
 * @date 2022/04/17
 */
@Component
public class JWTFilter extends BasicHttpAuthenticationFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        return super.preHandle(request, response);
    }
    /**
     * 判断请求头是否携带token
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //判断请求头有没有信息
        if (isLoginAttempt(request,response)){
            try {
                executeLogin(request,response);
            } catch (Exception e) {
                jumpToFailpage(response);
                e.printStackTrace();
            }
        }
        else {
            return false;
        }
        return true;
    }

    private void jumpToFailpage(ServletResponse response)  {
        HttpServletResponse response1 = (HttpServletResponse) response;
        try {
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断请求头是否携带token
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //获取请求头中的token
        String token = request1.getHeader("Authorization");
        return token == null?false:true;
    }
    /**
     * 执行登录校验
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest) request;
        String token = request1.getHeader("Authorization");
        Subject subject = getSubject(request, response);
        WebToken myJsonWebToken = new WebToken(token);
        subject.login(myJsonWebToken);
        return true;
    }
}
